import styles from "./styles.module.less";
import { useEffect } from "react";
import { Outlet } from "react-router-dom";
import { getHwndList, getLoginRecord, useMainStore } from "@/store/mainStore";
import SideBar from "@/components/side-bar";
import { Button, Modal, Select, Spin, Tooltip, message } from "antd";
import { useShallow } from "zustand/react/shallow";
import { ServerGetUserInfo } from "@go/app/ServerApp";
import { http } from "@/constant/status";
import { Icon } from "@iconify-icon/react";
import { HandleDrawWindowRectangle } from "@go/app/App";

function App() {
  const { sideTab, isLogin, token, currentHwnd, hwndList } = useMainStore(
    useShallow((state) => ({
      sideTab: state.sideTab,
      isLogin: state.isLogin,
      token: state.token,
      currentHwnd: state.currentHwnd,
      hwndList: state.hwndList,
    }))
  );

  async function getUserInfo(token: string) {
    useMainStore.setState({ appLoading: true });
    try {
      const res = await ServerGetUserInfo(token);
      if (res.code !== http.StatusOK) {
        message.error(res.msg);
      }
      console.log("用户信息", res.data);
      useMainStore.setState({ userInfo: res.data });
    } catch (err) {
      message.error(`获取用户信息失败: ${err}`);
    } finally {
      useMainStore.setState({ appLoading: false });
    }
  }

  useEffect(() => {
    if (isLogin && token !== "") {
      getUserInfo(token);
      getLoginRecord(token);
    } else {
      useMainStore.setState({ userInfo: {}, loginRecordList: [] });
    }
  }, [isLogin, token]);

  useEffect(() => {
    if (["/fish", "/collect"].includes(sideTab)) {
      getHwndList();
    }
  }, [sideTab]);

  return (
    <div id={styles.app}>
      <SideBar />
      <div className={styles.content}>
        <Outlet />
        <div
          className={styles.gamesWindow}
          style={{
            display: ["/fish", "/collect"].includes(sideTab) ? "flex" : "none",
            alignItems: "center",
          }}
        >
          <span>游戏窗口：</span>
          <Select
            size="small"
            style={{ width: 150 }}
            // notFoundContent="暂无游戏窗口"
            allowClear
            value={currentHwnd}
            options={hwndList}
            onChange={(value: number) => {
              useMainStore.setState({ currentHwnd: value });
              if (value) {
                HandleDrawWindowRectangle(value, 255, 500, 20);
              }
            }}
            placeholder="请选择"
          />
          <Tooltip title="刷新" placement="left">
            <Button
              size="small"
              shape="circle"
              color="primary"
              variant="text"
              icon={<Icon icon="material-symbols:refresh" />}
              onClick={getHwndList}
            />
          </Tooltip>
        </div>
      </div>
    </div>
  );
}

export default App;
